import axios from 'axios'
import router from '../router/index'
import { cookie } from 'vux'

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
    this.headers = {
      'Content-Type': 'application/json; charset=UTF-8'
    }
    this.headersWithToken = {
      'Content-Type': 'application/json; charset=UTF-8',
      'token':cookie.get('token') || '',
      'cid': cookie.get('userInfo') ? JSON.parse(cookie.get('userInfo')).id:''
    }
  }
  getInsideConfig (noToken) {
    if (noToken){
      // 登录等接口请求headers无需处理
      return {
        baseURL: this.baseUrl,
        headers: this.headers
      }
    } else {
      // 需要身份验证请求headers中加入token，cid

      return {
        baseURL: this.baseUrl,
        headers: this.headersWithToken
      }
    }
  }
  destroy (url) {
    delete this.queue[url]
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (this.queue[url] === true) return Promise.reject('请稍后...')
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      // 登录成功后操作
      if (url.indexOf('User/login') !== -1) {
        this.headersWithToken.token = res.data.content.token
        this.headersWithToken.cid = res.data.content.userInfo.id
      }
      this.destroy(url)
      const { data } = res
      if (data.status === 1) {
        return data.content
      } else {
        // this.$Message.error(data.msg)
        return Promise.reject(data.msg)
      }
    }, error => {
      this.destroy(url)
      // console.log(error)
      // if (error.response.status === 401) {
      //   tokenExpireAndToLogin()
      //   this.$vux.toast.show({
      //     text: '身份信息失效',
      //     type: 'cancel'
      //   })
      //   tokenExpireAndToLogin()
      // }
      return Promise.reject(error)
    })
  }
  request (options) {
    if (options.data) {
      Object.keys(options.data).forEach( item => {
        if ( (options.data[item] !== 0 && !options.data[item]) || ( options.data[item] instanceof Array && options.data[item].length === 0)  || ( options.data[item] instanceof Object && Object.keys(options.data[item]).length === 0) ) delete options.data[item]
      })
    }
    if (options.url === 'User/loginOut') {
      this.headersWithToken.token = ''
      this.headersWithToken.cid = ''
      return
    }
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(options.noToken), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

// 清除用户信息缓存信息并返回登录页面
// export const tokenExpireAndToLogin = () => {
//   Cookies.remove('token')
//   // Cookies.remove('accessList')
//   Cookies.remove('userId')
//   router.replace({
//     path: '/login',
//     query: {redirect: router.currentRoute.name}
//   })
// }

export default HttpRequest
